package util

import (
	"github.com/EDDYCJY/go-gin-app/pkg/setting"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var jwtSecret = []byte(setting.AppSetting.JwtSecret)

type Claims struct {
	UserId int `json:"user_id"`
	UserName string `json:"user_name"`
	jwt.StandardClaims
}

/**
生成token
 */
func CreateToken(userId int,userName string)(string,error)  {
	nowTime := time.Now()
	expireTime := nowTime.Add(6*time.Hour)

	claims := Claims{
		userId,
		userName,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer: "gin-blog",
		},
	}

	tokenClaim := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	token,err := tokenClaim.SignedString(jwtSecret)

	return token,err
}

/**
解析token
 */
func ParseToken(token string)(*Claims,error) {
	tokenClaims,err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret,nil
	})
	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims);ok&& tokenClaims.Valid {
			return claims,nil
		}
	}
	return nil,err
}


